﻿using System;
using System.Data;
using System.IO;
using System.Security.Permissions;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace CP.SharePoint.SiteStyles.EventReceivers
{
    public class SiteStylesReceiver : SPItemEventReceiver
    {
        /// <summary>
        /// Loops through all items in the site styles list and updates the farm
        /// properties bag with an XML representation of the data with in the
        /// list.
        /// </summary>
        /// <param name="list"></param>
        private void UpdateAvailableSiteStyles(SPList list)
        {
            try
            {
                SPFarm f = SPFarm.Local;

                DataTable dt = list.Items.GetDataTable();
                StringWriter writer = new StringWriter();
                dt.WriteXml(writer);

                if (f.Properties.ContainsKey(Resources.PropertyAvailableSiteStyles))
                {
                    f.Properties[Resources.PropertyAvailableSiteStyles] = writer.ToString();
                }
                else
                {
                    f.Properties.Add(Resources.PropertyAvailableSiteStyles, writer.ToString());
                }

                f.Update();
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("CP.SharePoint.SiteStyles - Site Styles Event Handler", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
            }
        }

        /// <summary>
        /// An item was added. Updates the farm properties bag with the
        /// list of all available site styles.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            UpdateAvailableSiteStyles(properties.List);
        }

        /// <summary>
        /// An item was updated. Updates the farm properties bag with the
        /// list of all available site styles.
        /// </summary>
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            UpdateAvailableSiteStyles(properties.List);
        }

        /// <summary>
        /// An item was deleted. Updates the farm properties bag with the
        /// list of all available site styles.
        /// </summary>
        public override void ItemDeleted(SPItemEventProperties properties)
        {
            UpdateAvailableSiteStyles(properties.List);
        }
    }
}
